package com.example.system.websocket;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Description:
 * @CreateTime 2020/4/4 19:01
 * @Version V1.0
 * @author hl
 */
public class WebSocketUtils {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketUtils.class);
    public static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<>();
    /**
     * 同步推送信息
     * @param session
     * @param message
     */
    private static void sendMessage(Session session, String message) {
        if (session == null) {
            logger.warn("webSocket session为空");
            return;
        }
        try {
            if (session.isOpen()) {
                synchronized (session) {
                    session.getBasicRemote().sendText(message);
                }
            }
        } catch (Exception e) {
            logger.error("webSocket发送同步信息失败", e);
            SessionSet.remove(session);
        }
    }

    public static void sendObject(Session session, Object object){
        if (session == null) {
            logger.warn("webSocket session为空");
            return;
        }
        try {
            if (session.isOpen()) {
                synchronized (session) {
                    session.getBasicRemote().sendObject(object);
                }
            }
        } catch (Exception e) {
            logger.error("webSocket发送同步信息失败", e);
            SessionSet.remove(session);
        }
    }

    /**
     * 给所用用户推送消息
     * @param message
     */
    public static void sendMessageAll(Object message) {
        if (message == null) {
            logger.warn("群发对象为空，将不进行消息推送");
            return;
        }
        SessionSet.forEach((session) -> sendObject(session, message));
    }
    /**
     * 给所用用户推送消息
     * @param message
     */
    public static void sendMessageAll(String message) {
        if (StringUtils.isEmpty(message)) {
            logger.warn("群发字符串为空，将不进行消息推送");
            return;
        }
        SessionSet.forEach((session) -> sendMessage(session, message));
    }

}
